﻿using iTool.ClusterComponent;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace iTool.Cloud.Database.KeyGeneratorProvider
{
    public class KeyWorkerService : iToolServiceBase<Dictionary<string, ushort>>, IKeyWorkerService
    {
        string tableName = String.Empty;
        public override Task OnActivateAsync()
        {
            this.tableName = base.GetStringKey();
            return base.OnActivateAsync();
        }

        public async Task<ushort> GetWorkerIdAsync()
        {
            this.State = this.State ?? new Dictionary<string, ushort>();
            if (this.State.TryGetValue(this.tableName, out ushort value))
            {
                value++;
                this.State[this.tableName] = value;
                await this.WriteStateAsync();
                return value;
            }
            else
            {
                this.State.Add(this.tableName, 1);
                await this.WriteStateAsync();
                return 1;
            }
        }
    }
}
